package art.yulang.factory;

import art.yulang.annotation.Autowired;
import art.yulang.annotation.Component;
import art.yulang.utils.TransactionManager;
import net.sf.cglib.proxy.Enhancer;
import net.sf.cglib.proxy.MethodInterceptor;
import net.sf.cglib.proxy.MethodProxy;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;

@Component("proxyFactory")
public class ProxyFactory {
    @Autowired
    private TransactionManager transactionManager;

    /**
     * JDK 动态代理获取代理对象
     * @param obj
     * @return
     */
    public Object getJDKProxyObject(Object obj){
        return Proxy.newProxyInstance(obj.getClass().getClassLoader(),  obj.getClass().getInterfaces(), new InvocationHandler() {
            @Override
            public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
                Object result = null;
                try {
                    transactionManager.transactionBegin();

                    result = method.invoke(obj, args);

                    transactionManager.commit();
                }catch (Exception e){
                    e.printStackTrace();
                    transactionManager.rollback();
                    throw e;
                }
                return result;
            }
        });
    }

    /**
     * cglib 动态代理获取代理对象
     * @param obj
     * @return
     */
    public Object getCglibProxyObject(Object obj){
        return Enhancer.create(obj.getClass(), new MethodInterceptor() {
            @Override
            public Object intercept(Object o, Method method, Object[] objects, MethodProxy methodProxy) throws Throwable {
                Object result = null;
                try {
                    transactionManager.transactionBegin();

                    result = method.invoke(obj, objects);

                    transactionManager.commit();
                }catch (Exception e){
                    e.printStackTrace();
                    transactionManager.rollback();
                    throw e;
                }
                return result;
            }
        });
    }
}
